﻿using SourceMaster.Model;
using SourceMaster.Util;
using SourceMaster.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace SourceMaster.UserControls
{
    /// <summary>
    /// ChangesetHistoryContextMenu.xaml 的交互逻辑
    /// </summary>
    public partial class ChangesetHistoryContextMenu : ContextMenu
    {
        public ChangesetHistoryContextMenu()
        {
            InitializeComponent();
        }
        
        private MyCommit GetCurrentSelectedCommit()
        {
            return ((DataGrid)PlacementTarget).SelectedItem as MyCommit;
        }

        private RepoViewModel GetRepositoryViewModel()
        {
            return ((DataGrid)PlacementTarget).DataContext as RepoViewModel;
        }

        private void OnOpened(object sender, System.Windows.RoutedEventArgs e)
        {
            var menuItemIndex = 0;
            var myCommit = GetCurrentSelectedCommit();
            var repositoryViewModel = GetRepositoryViewModel();
            var highlightColor = new SolidColorBrush()
            {
                Color = Color.FromRgb(8, 94, 160)
            };

            RemoveDynamicallyAddedMenuItems();

            if(myCommit == null)
            {
                return;
            }

            var numberOfCheckoutItems = 0;

            foreach(var myBranch in myCommit.Branches)
            {
                if(myBranch.Tip == myCommit && (repositoryViewModel.Head) != myBranch && myBranch.IsRemote == false)
                {
                    var text = new TextBlock();
                    text.Inlines.AddRange(new Inline[]
                    {
                        new Run("Checkout "),
                        new Run(myBranch.Name) {Foreground = highlightColor }
                    });

                    Items.Insert(menuItemIndex++, CreateMenuItem(text, "Checkout"));
                    numberOfCheckoutItems++;
                }
            }

            if(numberOfCheckoutItems == 0)
            {
                var text = new TextBlock();
                text.Inlines.AddRange(new Inline[]
                {
                    new Run("Checkout commit "),
                    new Run(myCommit.HashShort) {Foreground = highlightColor }
                });

                Items.Insert(menuItemIndex++, CreateMenuItem(text, "Checkout"));
                numberOfCheckoutItems++;
            }

            if(numberOfCheckoutItems > 1)
            {
                Items.Insert(menuItemIndex++, new Separator
                {
                    Tag = "Dynamic"
                });
            }

            var numberOfMergeItems = 0;
            foreach(MyBranch myBranch in myCommit.Branches)
            {
                if(myBranch.Tip == myCommit && myBranch != (MyBranch)repositoryViewModel.Head)
                {
                     // Add those that track this branch
                     foreach(MyBranch myBranchThatTracks in RepoUtil.GetBranchesThatTrack(myBranch, repositoryViewModel.MyBranches))
                    {
                        if(myBranchThatTracks.BehindBy>0&&
                            myBranchThatTracks.IsRemote == false&&
                            myBranch.Tip != myBranchThatTracks.Tip &&
                            repositoryViewModel.Head is DetachedHead == false &&
                            myBranch.Tip != myBranchThatTracks.Tip)
                        {
                            var text = new TextBlock();
                            text.Inlines.AddRange(new Inline[]
                            {
                                new Run("Merge "),
                                new Run(myBranch.Name) {Foreground = highlightColor },
                                new Run(" into "),
                                new Run(myBranchThatTracks.Name) {Foreground = highlightColor }
                            });

                            Items.Insert(menuItemIndex++, CreateMenuItem(text, "Merge"));
                            //numberOfCheckoutItems++;
                            numberOfMergeItems++;
                        }
                    }
                }

                if(myBranch.Tip == myCommit &&
                    myBranch != (MyBranch)repositoryViewModel.Head &&
                    repositoryViewModel.Head is DetachedHead == false &&
                    myCommit != ((MyBranch)repositoryViewModel.Head).Tip)
                {
                    var text = new TextBlock();
                    text.Inlines.AddRange(new Inline[]
                    {
                        new Run("Merge "),
                        new Run(myBranch.Name) {Foreground = highlightColor },
                        new Run(" into "),
                        new Run(((MyBranch)repositoryViewModel.Head).Name) {Foreground = highlightColor }
                    });

                    Items.Insert(menuItemIndex++, CreateMenuItem(text, "Merge"));
                    numberOfCheckoutItems++;
                }
            }

            if(numberOfMergeItems > 1)
            {
                Items.Insert(menuItemIndex++, new Separator
                {
                    Tag = "Dynamic"
                });
            }
        }

        private void RemoveDynamicallyAddedMenuItems()
        {
            IList<object> itemsToRemove = Items.Cast<object>().Where(mi =>
            {
                if (mi is MenuItem == false)
                    return false;

                var tag = ((MenuItem)mi).Tag;

                return tag != null && tag.ToString() == "Dynamic";
            }).ToList();

            foreach(MenuItem item in itemsToRemove)
            {
                Items.Remove(item);
            }
        }

        private MenuItem CreateMenuItem(object header, string icon)
        {
            return new MenuItem
            {
                Header = header,
                Tag = "Dynamic",
                Icon = new Image
                {
                    Stretch = Stretch.None
                    //Source = new BitmapImage(new Uri(@"pack://application:,,,/Resources/Icons/" + icon + ".png", UriKind.Absolute))
                }
            };
        }

        private MenuItem CreateMenuItem(object header)
        {
            return new MenuItem
            {
                Header = header,
                Tag = "Dynamic",
                Icon = new Image
                {
                    Stretch = Stretch.None
                }
            };
        }

        private void OnContextMenuOpening(object sender, ContextMenuEventArgs e)
        {
            var commit = GetCurrentSelectedCommit();

            if(commit == null)
            {
                e.Handled = true;
                return;
            }
        }


    }
}
